import { useState } from "react";
import { Image } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import ProForm, {
  ProFormDigit,
  ProFormRadio,
  ProFormDependency,
} from "@ant-design/pro-form";
import useCommonTable from "@/hooks/useCommonTable";

import { fetchList, add, update, remove } from "@/api/banner";
import UploadFile from "@/components/UploadFile";
import { bannerJumpOptions } from "@/const";
import Editor from "@/components/Editor";
import ChooseTable from "./components/ChooseTable";

const Banner = () => {
  const columns = [
    {
      title: "图片",
      dataIndex: "picture",
      search: false,
      render: (_, record) => {
        return <Image width={150} height={50} src={record.picture} />;
      },
    },
    {
      title: "跳转位置",
      dataIndex: "urlType",
      search: false,
      valueType: "select",
      fieldProps:{
        options: bannerJumpOptions,
      }
    },
    {
      title: "排序",
      dataIndex: "sorted",
      search: false,
    },
  ];

  const renderFormItem = ({ type, formRef }) => {
    return (
      <>
        <ProForm.Item
          name="picture"
          label="图片"
          rules={[{ required: true, message: "请上传图片" }]}
        >
          <UploadFile />
        </ProForm.Item>

        <ProFormDigit
          label="排序"
          name="sorted"
          placeholder="请输入排序"
          tooltip="数值越小越靠前"
          min={1}
          rules={[{ required: true, message: "请输入排序" }]}
        />

        <ProFormRadio.Group
          label="跳转位置"
          name="urlType"
          options={bannerJumpOptions}
          rules={[{ required: true, message: "请选择跳转位置" }]}
        />

        <ProFormDependency name={["urlType"]}>
          {({ urlType }) => {
            return urlType == 99 ? (
              <ProForm.Item
                name="richText"
                rules={[{ required: true, message: "请输入" }]}
              >
                <Editor />
              </ProForm.Item>
            ) : (
              urlType && (
                <ProForm.Item
                  name="articleId"
                  rules={[{ required: true, message: "请选择" }]}
                >
                  {/* 设置了key，每次切换跳转位置就会重新请求对应的接口 */}
                  <ChooseTable urlType={urlType} key={urlType} />
                </ProForm.Item>
              )
            );
          }}
        </ProFormDependency>
      </>
    );
  };

  return (
    <PageContainer>
      {useCommonTable({
        title: "轮播图",
        columns,
        renderFormItem,
        modalWidth: 1000,
        fetchList,
        add,
        update,
        remove,
        actionColumnWidth: 200,
        showCheckbox: false,
        labelCol: { span: 4 },
      })}
    </PageContainer>
  );
};

export default Banner;
